package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackInfoVo;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import io.swagger.v3.core.util.Json;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class AlbumReceiver {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AlbumInfoService albumInfoService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void trackInfoUpdate(String vo, Message message, Channel channel) throws IOException {
        if (!StringUtils.isEmpty(vo)){
            TrackStatMqVo trackStatMqVo = JSON.parseObject(vo, TrackStatMqVo.class);
            String businessNo = trackStatMqVo.getBusinessNo();
            Boolean result=redisTemplate.opsForValue().setIfAbsent(businessNo,1,10, TimeUnit.MINUTES);
            if (result){
                albumInfoService.trackUpdateStat(trackStatMqVo);
            }
            redisTemplate.delete(businessNo);
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException e) {
                e.printStackTrace();
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        }
    }
}
